//
//  AppDelegate.m
//  RedManStock
//
//  Created by lanou3g on 15/7/17.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "AppDelegate.h"
#import "RootTabBarController.h"
#import "HeadControlView.h"
#import "Scroll_PageControlView.h"
#import "ParameterHeader.h"
#import "MyCoreHandle.h"
#import "MyCoreEntrust.h"
#import "MyCorePosition.h"
#import "MyHandle.h"
#import "SimpleStock.h"
#import "User.h"
@interface AppDelegate ()
@property (nonatomic,retain) NSArray *entrustArray;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    RootTabBarController *rootVC=[[RootTabBarController alloc]init];
    self.window.rootViewController=rootVC;
    //加载外观
    [self setupOutLook];
    
    //获取当前的时间
    NSDateComponents *time=[MyHandle getNowDetailDate];
    if (time.weekday>1 && time.weekday<7) {
        NSThread *statusThread=[[NSThread alloc]initWithTarget:self selector:@selector(statusThreadAction:) object:nil];
        [statusThread start];
    }
    else{
        self.status=NO;
    }
    
    return YES;
}

#pragma mark - 设置外观 -
- (void)setupOutLook{
    
    [UINavigationBar appearance].barTintColor=TopBarColor;
    [UINavigationBar appearance].tintColor=[UIColor whiteColor];
    [UITableViewCell appearance].selectionStyle=UITableViewCellSelectionStyleNone;
    [UITabBar appearance].translucent=NO;
//        [UINavigationBar appearance].translucent=NO;
    //    [UITabBar appearance].translucent=NO;
}

#pragma mark - 重复检测当前的是否处于交易时间(5分钟一请求) -
- (void)statusThreadAction:(id)object{
    @autoreleasepool {
        self.statusTimer=[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(requestNowStatus) userInfo:nil repeats:YES];
        //因为120秒后才开启，所以第一次必须手动开启一下,而且必须在run之前!!!
        [self requestNowStatus];
        [[NSRunLoop currentRunLoop] run];
        
    }
    
}

#pragma mark 开始重复请求当前的股市状态，从程序开始，到程序结束，一直在执行
- (void)requestNowStatus{
    
    //请求股市的状态
    NSString *url=@"http://api.gongniucaijing.com/stock/info";
    [[MyHandle new] requestDataWithURLStr:url parameterBlock:^NSDictionary *{
        NSDictionary *dic=@{@"code":@"000001"};
        return dic;
    } successBlock:^(NSDictionary *responseDic) {
        int a=[[[responseDic objectForKey:@"data"] objectForKey:@"status"] intValue];
        
        //status=2表示交易中，status=4表示已休市
        //当处于交易状态
        if (a==2) {
            self.status=YES;
            //委托的数组存在，且entrustTimer并未开启，则开启子线程
            if ([[MyCoreHandle shareHandle] selectAllEntrust].count>0 && self.entrustTimer==nil) {
                NSThread *entrustThread=[[NSThread alloc]initWithTarget:self selector:@selector(entrustThreadAction) object:nil];
                [entrustThread start];
            }
        }
        else{
            self.status=NO;
            NSDateComponents *time=[MyHandle getNowDetailDate];
            NSArray *array=[[MyCoreHandle shareHandle] selectAllEntrust];
            if (time.hour<=17 && time.hour>=15 ) {
                
                float buySum=0;
                for (MyCoreEntrust *entrust in array) {
                    
                    //如果取消的是买入委托，需要求和，并返回给用户的可用资金
                    if ([entrust.which isEqualToString:@"冻结资金"]) {
                        buySum=buySum+[entrust.tradePrice floatValue];
                    }
                    
                    //如果取消卖出委托，需要分别恢复posion的可卖数量!!
                    else{
                        
                        MyCorePosition *position=[[MyCoreHandle shareHandle] selectPositionWithCode:entrust.stockCode];
                        position.availableVolume=[NSString stringWithFormat:@"%.0f",[position.availableVolume floatValue]+[entrust.volume floatValue]];
                        [self.managedObjectContext save:nil];
                    }
                }
                
                //取消委托，要返回用户的资金
                User *myUser=[NSKeyedUnarchiver unarchiveObjectWithFile: [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"user.plist"]];
                
                //只需要加上返回的买股票的钱
                myUser.availableAsset=[NSString stringWithFormat:@"%.2f",[myUser.availableAsset floatValue]+buySum];
                
                [NSKeyedArchiver archiveRootObject:myUser toFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"user.plist"]];
                
                //删除所有委托
                [[MyCoreHandle shareHandle] deleteAllMyEntrust];
            }
            
            //终止委托请求的定时器(如果它没有因为所有委托都结束后被终止的话)
            if (self.entrustTimer) {
                [self.entrustTimer invalidate];
                self.entrustTimer=nil;
            }
        }
        int cc=0;
        if (self.status) {
            cc=1;
        }
        else{
            cc=0;
        }
        NSLog(@"status=%d",cc);
    } errorBlock:^(NSError *error) {
        
    }];
}

#pragma mark 建立委托请求的定时器
- (void)entrustThreadAction{
    @autoreleasepool {
        self.entrustTimer=[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(requestEntrust) userInfo:nil repeats:YES];
        //第一次必须手动调用
        [self requestEntrust];
        [[NSRunLoop currentRunLoop] run];
        
    }
}

#pragma mark - 重复请求委托的信息(2分钟一请求) -
- (void)requestEntrust{
    //每次都要从数据库中去取
    self.entrustArray=[[MyCoreHandle shareHandle] selectAllEntrust];
    
//    如果委托数组为0，则终止entrustTimer,返回
    if (self.entrustArray.count==0) {
        [self.entrustTimer invalidate];
        self.entrustTimer=nil;
        return;
    }
    for (MyCoreEntrust *entrust in self.entrustArray) {
        NSString *url=@"http://api.gongniucaijing.com/stock/tradeinfo";
        [[MyHandle new] requestDataWithURLStr:url parameterBlock:^NSDictionary *{
            NSLog(@"----------entrust.stockCode=%@",entrust.stockCode);
            NSDictionary *dic=@{@"code":entrust.stockCode};
            return dic;
        } successBlock:^(NSDictionary *responseDic) {
            NSDictionary *dic=[responseDic objectForKey:@"data"];
            //如果是买入委托
            if ([entrust.which isEqualToString:@"冻结资金"]) {
                float a=[[dic objectForKey:@"sellPrice"][0] floatValue];
                //如果满足买入条件,而且a>1（主要是为了防止请求的数据位0.00的情况）
                if ([entrust.entrustPrice floatValue]>=a && a>1) {
                    
#warning 买入成功后，可用资金不能变，因为提交委托后，就已经改变了； 而股票市值会在每次进入页面后自动更新，所以这里也不用更新；而position中会在下面更新
                    
//                    //1.先改用户的账户信息
//                    User *myUser=[NSKeyedUnarchiver unarchiveObjectWithFile: [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"user.plist"]];
                    
//                    float aAf=[myUser.availableAsset floatValue]-[entrust.volume floatValue]*a;
//                    myUser.availableAsset=[NSString stringWithFormat:@"%.2f",aAf];
//                    myUser.totalPrice=[NSString stringWithFormat:@"%.2f",[myUser.totalAsset floatValue]-[myUser.availableAsset floatValue]];
                    
//                    [NSKeyedArchiver archiveRootObject:myUser toFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"user.plist"]];
                    
                    
                    //2.再将该交易加到position中
                    SimpleStock *stock=[[SimpleStock alloc]init];
                    stock.entrustPrice=[NSString stringWithFormat:@"%.2f",a];
                    stock.name=entrust.stockName;
                    stock.code=entrust.stockCode;
                    stock.which=entrust.which;
                    stock.volume=entrust.volume;
                    //最新一笔成交价，即是该股票的现价
                    stock.nowPrice=stock.entrustPrice;
                    
                    //3.存入Position
                    [[MyCoreHandle shareHandle] addMyPosition:stock];
                    
                    //4.最后再清掉该entrust（如果先清除掉的话，下面的代码就失效了）
                    [[MyCoreHandle shareHandle] deleteMyEntrust:entrust.entrustDate];
                }
            }
            //卖出委托
            else{
                float a=[[dic objectForKey:@"buyPrice"][0] floatValue];
                //如果满足卖出条件
                if ([entrust.entrustPrice floatValue]<=a && a>1) {
                    
                    
                    //1.先改用户的账户信息
                    User *myUser=[NSKeyedUnarchiver unarchiveObjectWithFile: [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"user.plist"]];
                    
                    float aAf=[myUser.availableAsset floatValue]+[entrust.volume floatValue]*a;
                    myUser.availableAsset=[NSString stringWithFormat:@"%.2f",aAf];
                    myUser.totalPrice=[NSString stringWithFormat:@"%.2f",[myUser.totalAsset floatValue]-[myUser.availableAsset floatValue]];
                    
                    //暂时不改变昨日总收益，今日收益和今日收益率
                    
                    [NSKeyedArchiver archiveRootObject:myUser toFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"user.plist"]];
                    
                    
                    //2.将该交易加到position中
                    SimpleStock *stock=[[SimpleStock alloc]init];
                    stock.entrustPrice=[NSString stringWithFormat:@"%.2f",a];
                    stock.name=entrust.stockName;
                    stock.code=entrust.stockCode;
                    stock.which=entrust.which;
                    stock.volume=entrust.volume;
                    //最新一笔成交价，即是该股票的现价
                    stock.nowPrice=stock.entrustPrice;
                    
                    //3.存入
                    [[MyCoreHandle shareHandle] addMyPosition:stock];
                    
                    //4.清掉该entrust
                    [[MyCoreHandle shareHandle] deleteMyEntrust:entrust.entrustDate];
                    
                }
            }
            
            
        } errorBlock:^(NSError *error) {
            
        }];
        
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [self saveContext];
    if (self.statusTimer) {
        [self.statusTimer invalidate];
        self.statusTimer=nil;
    }
    if (self.entrustTimer) {
        [self.entrustTimer invalidate];
        self.entrustTimer=nil;
    }
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.lanou3g.CoreDataMutiTableLesson" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"myCoreData" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"myCoreData.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}


@end
